'use strict';
angular.module('app.controllers')
  .controller('NewCtrl', function($scope, $state) {
    // body...
  })
  .controller('OverviewCtrl', function($scope, $state, $window, $filter) {
    var vm = this;
    vm.userRole = $window.sessionStorage.userRole;
    $scope.today = function() {
      $scope.dt = new Date();
    };
    $scope.today();

    $scope.clear = function() {
      $scope.dt = null;
    };
    $scope.open = function(ret, $event) {
      ret.opened = true;
    };

    $scope.setDate = function(year, month, day) {
      $scope.dt = new Date(year, month, day);
    };
    $scope.maxDate = $filter('date')(new Date, 'yyyy-MM-dd');

    $scope.dateOptions = {
      formatYear: 'yy',
      startingDay: 1
    };

    $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
    $scope.format = $scope.formats[0];

    $scope.status = {
      opened: false
    };

    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    var afterTomorrow = new Date();
    afterTomorrow.setDate(tomorrow.getDate() + 2);
    $scope.events =
      [{
        date: tomorrow,
        status: 'full'
      }, {
        date: afterTomorrow,
        status: 'partially'
      }];

  })
  .controller('ProfileController', function($scope, $state, UserService, $window) {
    var vm = this;
    vm.editable = true;
    vm.userRole = $window.sessionStorage.userRole;
    $scope.formData = {};
    UserService.get($window.sessionStorage.userId, $window.sessionStorage.userRole).then(function(ret) {
      vm.user = ret.data;
      if (vm.user.approvalStatus == 0 || vm.user.approvalStatus == 3) {
        vm.msg = "您还未通过审核，系统功能使用受限制，请先提交资料并审核!";
      } else if (vm.user.approvalStatus == 1) {
        vm.msg = "您的资料已经提交审核，请等待管理员审核！在未通过审核前可以继续修改资料。";
      } else if (vm.user.approvalStatus == 2) {
        vm.editable = true;
        vm.msg = "您的资料已经审核通过，如需要更改将会重新发起审核，审核时系统功能将会受限！";
      }
    })

    vm.updateProfile = function() {
      if (vm.userRole == 'shipper') {
        if (!vm.user.enterpriseName) {
          alert('请输入企业名称！');
          return false;
        }
      };
      var fitPhone = /^[1][358]\d{9}$/;
      if (!fitPhone.test(vm.user.contact.mobile)) {
        alert('手机格式错误！');
        return false;
      }
      vm.user.contactName = vm.user.contact.name;
      vm.user.contactPhone = vm.user.contact.telephone;
      vm.user.contactMobile = vm.user.contact.mobile;
      vm.user.email = vm.user.contact.email;
      vm.user.idCardNumberAttachment = $window.document.getElementById("id").value || null;
      vm.user.businessLicenseNumberAttachment = $window.document.getElementById("lic").value || null;
      vm.user.organizationNumberAttachment = $window.document.getElementById("org").value || null;
      vm.user.taxRegistrationNumberAttachment = $window.document.getElementById("tax").value || null;
      vm.user.bankLicenseNumberAttachment = $window.document.getElementById("bank").value || null;
      UserService.update($window.sessionStorage.userRole, vm.user).then(function(ret) {
        if (ret.data.code == 1) {
          alert(ret.data.value);
          return false;
        };
        UserService.submitProfile($window.sessionStorage.userRole, vm.user).then(function(ret) {
          if (ret.data.code == 1) {
            alert(ret.data.value);
            return false;
          };
          alert('提交成功! 请等待管理员审核');
          $state.go('home.profile', null, {
            reload: true
          });
        })

      })
    };
  })

.controller('VerifiedTuoyunController', function($scope, $state, UserService, ngDialog, $window) {
  var vm = this;
  vm.userRole = $window.sessionStorage.userRole;
  vm.currentPage = 1;
  vm.totalPages = 1;
  vm.pages = [];

  vm.load = function() {
    UserService.getAlreadyUsers('shipper', vm.currentPage).then(function(ret) {
      vm.users = ret.data.content;
      ret.data.totalElements == 0 ? vm.noRecord = true : vm.noRecord = false;
      vm.firstPage = ret.data.firstPage;
      vm.lastPage = ret.data.lastPage;
      vm.totalPages = ret.data.totalPages;
      var start = Math.max(0, vm.currentPage - 6);
      var end = Math.min(vm.currentPage + 6, vm.totalPages);
      for (var i = start; i < end; i++) {
        vm.pages.push(i + 1);
      }
    });
  };

  vm.load();
  vm.loadPage = function(page) {
    if (page > 0) {
      vm.currentPage = page;
      vm.load();
    }
  };

  vm.viewDetail = function(id) {
    $scope.id = id;
    ngDialog.open({
      template: 'views/tuoyunfang/detail.html',
      ariaAuto: false,
      className: 'ngdialog-theme-plain custom-width2',
      scope: $scope,
      preCloseCallback: function(value) {
        vm.load();
        return true;
      }
    });
  };

  vm.upgrade = function(id) {
    UserService.promoteShipper(id).then(function(ret) {
      if (ret.data.code == 1) {
        alert(ret.data.value);
        return false;
      }
      alert('成功升级为服务性企业会员！');
      vm.load();
    })
  }

})

.controller('WaitingTuoyunController', function($scope, $state, UserService, ngDialog) {
  var vm = this;
  vm.currentPage = 1;
  vm.totalPages = 1;
  vm.pages = [];

  vm.load = function() {
    UserService.getWaitUsers('shipper', vm.currentPage).then(function(ret) {
      vm.users = ret.data.content;
      ret.data.totalElements == 0 ? vm.noRecord = true : vm.noRecord = false;
      vm.firstPage = ret.data.firstPage;
      vm.lastPage = ret.data.lastPage;
      vm.totalPages = ret.data.totalPages;
      var start = Math.max(0, vm.currentPage - 6);
      var end = Math.min(vm.currentPage + 6, vm.totalPages);
      for (var i = start; i < end; i++) {
        vm.pages.push(i + 1);
      }
    });
  };

  vm.load();
  vm.loadPage = function(page) {
    if (page > 0) {
      vm.currentPage = page;
      vm.load();
    }
  };
  vm.viewDetail = function(id) {
    $scope.id = id;
    ngDialog.open({
      template: 'views/tuoyunfang/detail.html',
      ariaAuto: false,
      className: 'ngdialog-theme-plain custom-width2',
      scope: $scope,
      preCloseCallback: function(value) {
        vm.load();
        return true;
      }
    });
  };
})

.controller('NewTuoyunController', function($scope, UserService, ngDialog) {
    var vm = this;

    vm.currentPage = 1;
    vm.totalPages = 1;
    vm.pages = [];

    vm.load = function() {
      UserService.getNewUsers('shipper', vm.currentPage).then(function(ret) {
        vm.users = ret.data.content;
        ret.data.totalElements == 0 ? vm.noRecord = true : vm.noRecord = false;
        vm.firstPage = ret.data.firstPage;
        vm.lastPage = ret.data.lastPage;
        vm.totalPages = ret.data.totalPages;
        var start = Math.max(0, vm.currentPage - 6);
        var end = Math.min(vm.currentPage + 6, vm.totalPages);
        for (var i = start; i < end; i++) {
          vm.pages.push(i + 1);
        }
      });
    };

    vm.load();
    vm.loadPage = function(page) {
      if (page > 0) {
        vm.currentPage = page;
        vm.load();
      }
    };
    vm.viewDetail = function(id) {
      $scope.id = id;
      ngDialog.open({
        template: 'views/tuoyunfang/detail.html',
        ariaAuto: false,
        className: 'ngdialog-theme-plain custom-width2',
        scope: $scope,
        preCloseCallback: function(value) {
          vm.load();
          return true;
        }
      });
    };
  })
  .controller('BlackTuoyunController', function($scope, $state, UserService, ngDialog) {
    var vm = this;
    vm.currentPage = 1;
    vm.totalPages = 1;
    vm.pages = [];

    vm.load = function() {
      UserService.getBlackList('shipper', vm.currentPage).then(function(ret) {
        vm.users = ret.data.content;
        ret.data.totalElements == 0 ? vm.noRecord = true : vm.noRecord = false;
        vm.firstPage = ret.data.firstPage;
        vm.lastPage = ret.data.lastPage;
        vm.totalPages = ret.data.totalPages;
        var start = Math.max(0, vm.currentPage - 6);
        var end = Math.min(vm.currentPage + 6, vm.totalPages);
        for (var i = start; i < end; i++) {
          vm.pages.push(i + 1);
        }
      });
    };

    vm.load();
    vm.loadPage = function(page) {
      if (page > 0) {
        vm.currentPage = page;
        vm.load();
      }
    };
    vm.viewDetail = function(id) {
      $scope.id = id;
      ngDialog.open({
        template: 'views/tuoyunfang/detail.html',
        ariaAuto: false,
        className: 'ngdialog-theme-plain custom-width2',
        scope: $scope,
        preCloseCallback: function(value) {
          vm.load();
          return true;
        }
      });
    };

  })

.controller('TuoyunDetailCtrl', function($scope, $state, $stateParams, UserService, ngDialog) {
    var vm = this;
    vm.userRole = window.sessionStorage.userRole;

    UserService.get($scope.id, 'shipper').then(function(ret) {
      vm.user = ret.data;
    })

    vm.verify = function(id, pass) {
      if (pass) {
        UserService.verifyUser('shipper', vm.user.id, 'approve').then(function(ret) {
          alert('审核通过!');
          ngDialog.closeAll();
        })
      } else {
        UserService.verifyUser('shipper', vm.user.id, 'deny').then(function(ret) {
          alert('审核不通过!');
          ngDialog.closeAll();
        })
      }
    };

    vm.addBlack = function(userId) {
      UserService.setBlack(userId, 'shipper').then(function(ret) {
        ngDialog.closeAll();
      })
    };
    vm.cancelBlack = function(userId) {
      UserService.cancelBlack(userId, 'shipper').then(function(ret) {
        ngDialog.closeAll();
      })
    }

  })
  .controller('TuoyunSearchCtrl', function($scope, UserService, ngDialog) {
    var vm = this;
    vm.user = {};
    vm.approvalStatus = "0";
    vm.noRecord = false;
    vm.currentPage = 1;
    vm.totalPages = 1;
    vm.pages = [];
    vm.load = function() {
      if (vm.approvalStatus == "0") {
        delete vm.user.approvalStatus;
      } else if (vm.approvalStatus == "1") vm.user.approvalStatus = 0;
      else if (vm.approvalStatus == "2") vm.user.approvalStatus = 1;
      else if (vm.approvalStatus == "3") vm.user.approvalStatus = 2;
      else if (vm.approvalStatus == "4") vm.user.approvalStatus = 3;
      UserService.searchShipper(vm.user).then(function(ret) {
        vm.users = angular.copy(ret.data.content);
        if (vm.users.length < 1) {
          vm.noRecord = true;
        } else {
          vm.noRecord = false;
          vm.firstPage = ret.data.firstPage;
          vm.lastPage = ret.data.lastPage;
          vm.totalPages = ret.data.totalPages;
          var start = Math.max(0, vm.currentPage - 6);
          var end = Math.min(vm.currentPage + 6, vm.totalPages);
          for (var i = start; i < end; i++) {
            vm.pages.push(i + 1);
          };
        }

      })
    }
    vm.searchUser = function() {
      vm.load();
    };

    vm.loadPage = function(page) {
      if (page > 0) {
        vm.currentPage = page;
        vm.load();
      }
    };
    vm.viewDetail = function(id) {
      $scope.id = id;
      ngDialog.open({
        template: 'views/tuoyunfang/detail.html',
        ariaAuto: false,
        className: 'ngdialog-theme-plain custom-width2',
        scope: $scope,
        preCloseCallback: function(value) {
          vm.load();
          return true;
        }
      });
    };
  })
  .controller('NewUserCtrl', function($scope, $state, UserService, ngDialog, $window) {
    var vm = this;
    vm.user = null;
    vm.updateProfile = function() {
      if (vm.userRole != 'shipper') {
        vm.user.idCardNumberAttachment = $window.document.getElementById("id").value || null;
      } else {
        vm.user.businessLicenseNumberAttachment = $window.document.getElementById("lic").value || null;
        vm.user.organizationNumberAttachment = $window.document.getElementById("org").value || null;
        vm.user.taxRegistrationNumberAttachment = $window.document.getElementById("tax").value || null;
        vm.user.bankLicenseNumberAttachment = $window.document.getElementById("bank").value || null;
      }

      UserService.update(vm.userRole, vm.user).then(function(ret) {
        if (ret.data.code == 1) {
          alert(ret.data.value);
          return false;
        }
        alert('添加成功！');
        if (vm.userRole != 'shipper') {
          $state.go('home.chengyunListNew', null, {
            reload: true
          });
        } else {
          $state.go('home.tuoyunListNew', null, {
            reload: true
          });
        };
      })
    };

    vm.newUser = function(role) {
      var fitPhone = /^[1][358]\d{9}$/;
      if (!vm.user) {
        alert('请输入用户信息！');
      }
      if (!fitPhone.test(vm.user.contactMobile)) {
        alert("手机号码格式错误!");
        return false;
      }
      if ($scope.pwd1 == null || $scope.pwd2 == null) {
        alert('请输入密码！');
        return false;
      }
      if ($scope.pwd1 != $scope.pwd2) {
        alert("两次密码输入不一致");
        return false;
      }
      vm.userRole = role;
      vm.user.password = hex_md5($scope.pwd1);
      vm.updateProfile();
    };
  })
  .controller('VerifiedChengyunController', function($scope, $state, UserService, ngDialog) {
    var vm = this;
    vm.currentPage = 1;
    vm.totalPages = 1;
    vm.pages = [];

    vm.load = function() {
      UserService.getAlreadyUsers('carrier', vm.currentPage).then(function(ret) {
        vm.users = ret.data.content;
        ret.data.totalElements == 0 ? vm.noRecord = true : vm.noRecord = false;
        vm.firstPage = ret.data.firstPage;
        vm.lastPage = ret.data.lastPage;
        vm.totalPages = ret.data.totalPages;
        var start = Math.max(0, vm.currentPage - 6);
        var end = Math.min(vm.currentPage + 6, vm.totalPages);
        for (var i = start; i < end; i++) {
          vm.pages.push(i + 1);
        }
      });
    };

    vm.load();
    vm.loadPage = function(page) {
      if (page > 0) {
        vm.currentPage = page;
        vm.load();
      }
    };
    vm.viewDetail = function(id) {
      $scope.id = id;
      ngDialog.open({
        template: 'views/chengyunfang/detail.html',
        ariaAuto: false,
        className: 'ngdialog-theme-plain custom-width2',
        scope: $scope,
        preCloseCallback: function(value) {
          vm.load();
          return true;
        }
      });
    };
  })

.controller('WaitingChengyunController', function($scope, $state, UserService, ngDialog) {
  var vm = this;

  vm.currentPage = 1;
  vm.totalPages = 1;
  vm.pages = [];

  vm.load = function() {
    UserService.getWaitUsers('carrier', vm.currentPage).then(function(ret) {
      vm.users = ret.data.content;
      ret.data.totalElements == 0 ? vm.noRecord = true : vm.noRecord = false;
      vm.firstPage = ret.data.firstPage;
      vm.lastPage = ret.data.lastPage;
      vm.totalPages = ret.data.totalPages;
      var start = Math.max(0, vm.currentPage - 6);
      var end = Math.min(vm.currentPage + 6, vm.totalPages);
      for (var i = start; i < end; i++) {
        vm.pages.push(i + 1);
      }
    });
  };

  vm.load();
  vm.loadPage = function(page) {
    if (page > 0) {
      vm.currentPage = page;
      vm.load();
    }
  };
  vm.viewDetail = function(id) {
    $scope.id = id;
    ngDialog.open({
      template: 'views/chengyunfang/detail.html',
      ariaAuto: false,
      className: 'ngdialog-theme-plain custom-width2',
      scope: $scope,
      preCloseCallback: function(value) {
        vm.load();
        return true;
      }
    });
  };
})

.controller('BlackChengyunController', function($scope, $state, UserService, ngDialog) {
  var vm = this;
  vm.currentPage = 1;
  vm.totalPages = 1;
  vm.pages = [];

  vm.load = function() {
    UserService.getBlackList('carrier', vm.currentPage).then(function(ret) {
      vm.users = ret.data.content;
      ret.data.totalElements == 0 ? vm.noRecord = true : vm.noRecord = false;
      vm.firstPage = ret.data.firstPage;
      vm.lastPage = ret.data.lastPage;
      vm.totalPages = ret.data.totalPages;
      var start = Math.max(0, vm.currentPage - 6);
      var end = Math.min(vm.currentPage + 6, vm.totalPages);
      for (var i = start; i < end; i++) {
        vm.pages.push(i + 1);
      }
    });
  };

  vm.load();
  vm.loadPage = function(page) {
    if (page > 0) {
      vm.currentPage = page;
      vm.load();
    }
  };
  vm.viewDetail = function(id) {
    $scope.id = id;
    ngDialog.open({
      template: 'views/chengyunfang/detail.html',
      ariaAuto: false,
      className: 'ngdialog-theme-plain custom-width2',
      scope: $scope,
      preCloseCallback: function(value) {
        vm.load();
        return true;
      }
    });
  };
})

.controller('NewChengyunController', function($scope, $rootScope, $state, UserService, ngDialog) {
  var vm = this;

  vm.currentPage = 1;
  vm.totalPages = 1;
  vm.pages = [];

  vm.load = function() {
    UserService.getNewUsers('carrier', vm.currentPage).then(function(ret) {
      vm.users = ret.data.content;
      ret.data.totalElements == 0 ? vm.noRecord = true : vm.noRecord = false;
      vm.firstPage = ret.data.firstPage;
      vm.lastPage = ret.data.lastPage;
      vm.totalPages = ret.data.totalPages;
      var start = Math.max(0, vm.currentPage - 6);
      var end = Math.min(vm.currentPage + 6, vm.totalPages);
      for (var i = start; i < end; i++) {
        vm.pages.push(i + 1);
      }
    });
  };

  vm.load();
  vm.loadPage = function(page) {
    if (page > 0) {
      vm.currentPage = page;
      vm.load();
    }
  };
  vm.viewDetail = function(id) {
    $scope.id = id;
    ngDialog.open({
      template: 'views/chengyunfang/detail.html',
      ariaAuto: false,
      className: 'ngdialog-theme-plain custom-width2',
      scope: $scope,
      preCloseCallback: function(value) {
        vm.load();
        return true;
      }
    });
  };
})

.controller('ChengyunDetailCtrl', function($scope, $state, $stateParams, UserService, ngDialog) {
    var vm = this;
    vm.userRole = window.sessionStorage.userRole;
    UserService.get($scope.id, 'carrier').then(function(ret) {
      vm.user = ret.data;
    });

    vm.verify = function(id, pass) {
      if (pass) {
        UserService.verifyUser('carrier', vm.user.id, 'approve').then(function(ret) {
          alert('审核通过!');
          ngDialog.closeAll();
        })
      } else {
        UserService.verifyUser('carrier', vm.user.id, 'deny').then(function(ret) {
          alert('审核不通过!');
          ngDialog.closeAll();
        })
      }
    };
    vm.addBlack = function(userId) {
      UserService.setBlack(userId, 'carrier').then(function(ret) {
        ngDialog.closeAll();
      })
    };
    vm.cancelBlack = function(userId) {
      ngDialog.closeAll();
      UserService.cancelBlack(userId, 'carrier').then(function(ret) {
        ngDialog.closeAll();
      })
    };
    vm.viewDrivers = function(userId) {
      $scope.userId = userId;
      ngDialog.open({
        template: 'views/tuoyunfang/drivers.html',
        ariaAuto: false,
        className: 'ngdialog-theme-plain custom-width2',
        scope: $scope
      });
    };
    vm.viewCars = function(userId) {
      $scope.userId = userId;
      ngDialog.open({
        template: 'views/tuoyunfang/cars.html',
        ariaAuto: false,
        className: 'ngdialog-theme-plain custom-width2',
        scope: $scope
      });
    }

  })
  .controller('ChengyunSearchCtrl', function($scope, UserService, ngDialog) {
    var vm = this;
    vm.user = {};
    vm.approvalStatus = "0";
    vm.noRecord = false;
    vm.currentPage = 1;
    vm.totalPages = 1;
    vm.pages = [];

    vm.load = function() {
      if (vm.approvalStatus == "0") {
        delete vm.user.approvalStatus;
      } else if (vm.approvalStatus == "1") vm.user.approvalStatus = 0;
      else if (vm.approvalStatus == "2") vm.user.approvalStatus = 1;
      else if (vm.approvalStatus == "3") vm.user.approvalStatus = 2;
      else if (vm.approvalStatus == "4") vm.user.approvalStatus = 3;
      UserService.searchCarrier(vm.user).then(function(ret) {
        vm.users = angular.copy(ret.data.content);
        if (vm.users.length < 1) {
          vm.noRecord = true;
        } else {
          vm.noRecord = false;
          vm.firstPage = ret.data.firstPage;
          vm.lastPage = ret.data.lastPage;
          vm.totalPages = ret.data.totalPages;
          var start = Math.max(0, vm.currentPage - 6);
          var end = Math.min(vm.currentPage + 6, vm.totalPages);
          for (var i = start; i < end; i++) {
            vm.pages.push(i + 1);
          };
        }

      })
    }
    vm.searchUser = function() {
      vm.load();
    };

    vm.loadPage = function(page) {
      if (page > 0) {
        vm.currentPage = page;
        vm.load();
      };
    };
    vm.viewDetail = function(id) {
      $scope.id = id;
      ngDialog.open({
        template: 'views/chengyunfang/detail.html',
        ariaAuto: false,
        className: 'ngdialog-theme-plain custom-width2',
        scope: $scope
      });
    };
  })
  .controller('ViewMyCarsCtrl', function($scope, $window, CarService, ngDialog) {
    var vm = this;
    vm.userRole = $window.sessionStorage.userRole;
    vm.noRecord = true;
    vm.currentPage = 1;
    vm.totalPages = 1;
    vm.pages = [];

    vm.load = function() {
      vm.pages = [];
      CarService.search({
        'carrierId': $scope.userId
      }, vm.currentPage).then(function(ret) {
        vm.cars = ret.data.content;
        ret.data.totalElements == 0 ? vm.noRecord = true : vm.noRecord = false;
        vm.firstPage = ret.data.firstPage;
        vm.lastPage = ret.data.lastPage;
        vm.totalPages = ret.data.totalPages;
        var start = Math.max(0, vm.currentPage - 6);
        var end = Math.min(vm.currentPage + 6, vm.totalPages);
        for (var i = start; i < end; i++) {
          vm.pages.push(i + 1);
        }
      });
    };

    vm.load();

    vm.loadPage = function(page) {
      if (page > 0) {
        vm.currentPage = page;
        vm.load();
      }
    };
    vm.viewDetail = function(carId) {
      $scope.carId = carId;
      ngDialog.open({
        template: 'views/car/detail.html',
        ariaAuto: false,
        className: 'ngdialog-theme-plain custom-width',
        scope: $scope
      })
    }
  })
  .controller('ViewMyDriversCtrl', function($scope, ngDialog, DriverService) {
    var vm = this;
    vm.currentPage = 1;
    vm.totalPages = 1;
    vm.pages = [];

    vm.load = function() {
      vm.pages = [];
      DriverService.getCarrierDriver($scope.userId, vm.currentPage).then(function(ret) {
        vm.drivers = ret.data.content;
        ret.data.totalElements == 0 ? vm.noRecord = true : vm.noRecord = false;
        vm.firstPage = ret.data.firstPage;
        vm.lastPage = ret.data.lastPage;
        vm.totalPages = ret.data.totalPages;
        var start = Math.max(0, vm.currentPage - 6);
        var end = Math.min(vm.currentPage + 6, vm.totalPages);
        for (var i = start; i < end; i++) {
          vm.pages.push(i + 1);
        }
      });
    };

    vm.load();

    vm.loadPage = function(page) {
      if (page > 0) {
        vm.currentPage = page;
        vm.load();
      }
    };
    vm.viewDetail = function(driverId) {
      $scope.driverId = driverId;
      ngDialog.open({
        template: 'views/driver/detail.html',
        ariaAuto: false,
        className: 'ngdialog-theme-plain custom-width',
        scope: $scope
      })
    }

  })